package com.shuqing.download.engine.distribute.dispatch;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.shuqing.download.engine.DefaultHandler;
import com.shuqing.download.engine.config.EngineConfig;
import com.shuqing.download.engine.constants.ActuatorEnum;
import com.shuqing.download.engine.constants.EventEnum;
import com.shuqing.download.engine.distribute.dispatch.monitor.MonitorLeader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 调度器 顶层接口
 * @author wangshuqing
 * @date 2023/3/4 8:50
 */
@Slf4j
public abstract class AbstractDispatch implements DefaultHandler {

    @Autowired
    protected EngineConfig engineConfig;
    @Autowired
    protected MonitorLeader monitorLeader;
    /**
    * 任务调用方法
     * 如果成功执行就执行 返回true
    * @date 2023/3/4 8:53
    * @author wangshuqing
    * @param context  上下文
     *@return boolean 是否成功结束 ，如果失败一抛出异常
    * */
    public boolean dispatch(TaskContext context,String actuatorCode){
        List<AbstractActuator> actuators=getAllActuator();
        if(CollectionUtil.isEmpty(actuators)){
            log.info("执行器为空");
            return false;
        }
        for(AbstractActuator actuator:actuators){
            ActuatorEnum actuatorEnum=actuator.actuatorEnum();
            if(StrUtil.equals(actuatorCode,actuatorEnum.getCode())){
                monitorLeader.assignSuccessEvent(context, EventEnum.ACTUATOR_START,actuatorEnum.getDesc());
                actuator.execute(context);
                monitorLeader.assignSuccessEvent(context, EventEnum.ACTUATOR_FINISH,actuatorEnum.getDesc());
                return true;
            }
        }
        return false;
    }


    /**
    * 获取所有执行器
    * @date 2023/3/5 15:34
    * @author wangshuqing
     * @param
     *@return java.util.List<com.shuqing.download.engine.distribute.dispatch.AbstractActuator>
    * */
    public abstract <T extends AbstractActuator> List<T> getAllActuator();



}
